﻿using System;
using System.Globalization;
using System.Linq;
using ATM.Terminal.Database;
using ATM.Terminal.Models;
using ATM.Terminal.Rendering.Base;
using ATM.Terminal.Screens.Base;
using ATM.Terminal.Shared;

namespace ATM.Terminal.Screens
{
    public class AuthenticationScreen : ScreenBase
    {
        private string _buffer;

        public AuthenticationScreen()
        {
            _buffer = string.Empty;
        }

        public override void Render(RenderTargetBase renderTarget)
        {
            renderTarget.Render(new ScreenModel()
            {
                Title = "Authentication Screen",
                Content = new[]
                        {
                            "Please authenticate:",
                            string.Format("PIN: {0}", _buffer.Mask())
                        }
            });
        }

        public override void ProcessInput(ConsoleKeyInfo input)
        {
            switch (input.Key)
            {
                case ConsoleKey.Backspace:
                    _buffer = string.Empty;
                    break;
                case ConsoleKey.Enter:
                    var pin = int.Parse(_buffer);

                    LookupAccountAndShowInformation(pin);
                    break;
                default: //Only allow numbers.
                    if(input.KeyChar.ToString(CultureInfo.InvariantCulture).IsNumeric())
                        _buffer += input.KeyChar;
                    break;
            }
        }

        private void LookupAccountAndShowInformation(int pin)
        {
            var account = DummyDatabase.Accounts.FirstOrDefault(accountModel => accountModel.AccountPIN.Equals(pin));

            if (account == null)
            {
                base.RaiseScreenChange(new ExceptionScreen("This account has not been found..."));
            }
            else
            {
                base.RaiseScreenChange(new InformationScreen(account));
            }
        }
    }
}
